# -*- coding: utf-8 -*-

from odoo import models, fields, api


class SaleOrder(models.Model):
    _inherit = 'sale.order'
    remark = fields.Char(string='备注')

    attachment_number = fields.Integer('附件数量', compute='_compute_attachment_number')

    def action_get_attachment_view(self):
        res = self.env['ir.actions.act_window'].for_xml_id('base', 'action_attachment')
        res['domain'] = [('res_model', '=', 'sale.order.line'), ('res_id', 'in', self.order_line.ids)]
        res['context'] = {
            'default_res_model': 'sale.order',
            'default_res_id': self.id,
            'create': False,
            'edit': False,
        }

    def _compute_attachment_number(self):
        for sheet in self:
            sheet.attachment_number = sum(sheet.order_line.mapped('attachment_number'))


class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    attachment_number = fields.Integer('附件数量', compute='_compute_attachment_number')

    def _compute_attachment_number(self):
        attachment_data = self.env['ir.attachment'].read_group(
            [('res_model', '=', 'sale.order.line'), ('res_id', 'in', self.ids)], ['res_id'], ['res_id'])
        attachment = dict((data['res_id'], data['res_id_count']) for data in attachment_data)
        for expense in self:
            expense.attachment_number = attachment.get(expense.id, 0)

    def action_get_attachment_view(self):
        self.ensure_one()
        res = self.env['ir.actions.act_window'].for_xml_id('base', 'action_attachment')
        res['domain'] = [('res_model', '=', 'sale.order.line'), ('res_id', 'in', self.ids)]
        res['context'] = {'default_res_model': 'sale.order.line', 'default_res_id': self.id}
        return res
